package com.ruoyi.zxjd.work.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.zxjd.common.CommonConstants;
import com.ruoyi.zxjd.common.domain.CommonUserVO;
import com.ruoyi.zxjd.common.mapper.CommonMapper;
import com.ruoyi.zxjd.work.domain.WorkArrange;
import com.ruoyi.zxjd.work.domain.WorkHandle;
import com.ruoyi.zxjd.work.domain.WorkProgress;
import com.ruoyi.zxjd.work.domain.WorkTemplate;
import com.ruoyi.zxjd.work.mapper.WorkArrangeMapper;
import com.ruoyi.zxjd.work.service.IWorkArrangeService;
import com.ruoyi.zxjd.work.service.IWorkHandleService;
import com.ruoyi.zxjd.work.service.IWorkTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

/**
 * 工作安排Service业务层处理
 * 
 * @author lcc
 * @date 2021-01-26
 */
@Service
public class WorkArrangeServiceImpl implements IWorkArrangeService 
{
    @Autowired
    private WorkArrangeMapper workArrangeMapper;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private IWorkTemplateService workTemplateService;
    @Autowired
    private IWorkHandleService workHandleService;

    /**
     * 查询工作安排
     * 
     * @param arrangeId 工作安排ID
     * @return 工作安排
     */
    @Override
    public WorkArrange selectWorkArrangeById(Long arrangeId)
    {
        WorkArrange workArrange = workArrangeMapper.selectWorkArrangeById(arrangeId);
        String[] userIds = null;
        if(workArrange.getTotal()>0){
            userIds = workArrangeMapper.selectReceiveUserByArrangeId(arrangeId);
        }
        workArrange.setUserIds(userIds);
        return workArrange;
    }

    /**
     * 查询工作安排列表
     * 
     * @param workArrange 工作安排
     * @return 工作安排
     */
    @Override
    public List<WorkArrange> selectWorkArrangeList(WorkArrange workArrange)
    {
        return workArrangeMapper.selectWorkArrangeList(workArrange);
    }

    /**
     * 新增工作安排
     * 
     * @param workArrange 工作安排
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWorkArrange(WorkArrange workArrange)
    {
        workArrange.setCreateBy(ShiroUtils.getLoginName());
        workArrange.setCreateTime(DateUtils.getNowDate());
        workArrange.setUpdateBy(ShiroUtils.getLoginName());
        workArrange.setUpdateTime(DateUtils.getNowDate());
        workArrange.setUserId(ShiroUtils.getUserId());
        workArrange.setUserName(ShiroUtils.getSysUser().getUserName());
        workArrange.setDeptId(ShiroUtils.getSysUser().getDeptId());
        workArrange.setDeptName(ShiroUtils.getSysUser().getDept().getDeptName());
        workArrange.setUnfillTotal(workArrange.getTotal());
        if(StringUtils.isNotNull(workArrange.getWarningDate())){
            workArrange.setWarningTips(CommonConstants.TIPS);
        }

        Long templateId = workArrange.getTemplateId();
        WorkTemplate workTemplate = workTemplateService.selectWorkTemplateById(templateId);
        String formContent = workTemplate.getTemplateContent();
        if(StringUtils.isEmpty(formContent)){
            throw new BusinessException("未定义模板内容");
        }
        workArrange.setTemplateName(workTemplate.getTemplateName());

        int rows = workArrangeMapper.insertWorkArrange(workArrange);
        insertWorkProgress(workArrange);
        return rows;
    }

    /**
     * 修改工作安排
     * 
     * @param workArrange 工作安排
     * @return 结果
     */
    
    @Override
    @Transactional
    public int updateWorkArrange(WorkArrange workArrange)
    {
        workArrange.setUpdateBy(ShiroUtils.getLoginName());
        workArrange.setUpdateTime(DateUtils.getNowDate());
        workArrange.setUserId(ShiroUtils.getUserId());
        workArrange.setUserName(ShiroUtils.getSysUser().getUserName());
        workArrange.setDeptId(ShiroUtils.getSysUser().getDeptId());
        workArrange.setDeptName(ShiroUtils.getSysUser().getDept().getDeptName());
        workArrange.setUnfillTotal(workArrange.getTotal());
        if(StringUtils.isNotNull(workArrange.getWarningDate())){
            workArrange.setWarningTips(CommonConstants.TIPS);
        }
        Long templateId = workArrange.getTemplateId();
        WorkTemplate workTemplate = workTemplateService.selectWorkTemplateById(templateId);
        String formContent = workTemplate.getTemplateContent();
        if(StringUtils.isEmpty(formContent)){
            throw new BusinessException("未定义模板内容");
        }
        workArrange.setTemplateName(workTemplate.getTemplateName());

        workArrangeMapper.deleteWorkProgressByArrangeId(workArrange.getArrangeId());
        insertWorkProgress(workArrange);
        return workArrangeMapper.updateWorkArrange(workArrange);
    }

    /**
     * 删除工作安排对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteWorkArrangeByIds(String ids)
    {
        Long[] arrangeIds = Convert.toLongArray(ids);
        for (Long arrangeId : arrangeIds) {
            WorkArrange workArrange = workArrangeMapper.selectWorkArrangeById(arrangeId);
            if(!StringUtils.equals(CommonConstants.DRAFT, workArrange.getStatus())){
                throw new BusinessException(String.format("只有“草稿”状态的数据才能删除", workArrange.getArrangeTitle()));
            }
        }
        workArrangeMapper.deleteWorkProgressByArrangeIds(Convert.toStrArray(ids));
        workArrangeMapper.deleteWorkFormByArrangeIds(Convert.toStrArray(ids));
        return workArrangeMapper.deleteWorkArrangeByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除工作安排信息
     * 
     * @param arrangeId 工作安排ID
     * @return 结果
     */
    @Override
    public int deleteWorkArrangeById(Long arrangeId)
    {
        workArrangeMapper.deleteWorkProgressByArrangeId(arrangeId);
        workArrangeMapper.deleteWorkFormByArrangeId(arrangeId);
        return workArrangeMapper.deleteWorkArrangeById(arrangeId);
    }

    /**
     * 新增工作进度信息
     * 
     * @param workArrange 工作安排对象
     */
    public void insertWorkProgress(WorkArrange workArrange)
    {
        String[] userIds = workArrange.getUserIds();
        List<CommonUserVO> list = null;
        String releaseScope = workArrange.getReleaseScope();
        if(CommonConstants.AllUSER.equals(releaseScope)){
            list = commonMapper.listActiveUser(null,null);
        }else{
            list = commonMapper.listActiveUserByIds(userIds);
        }
        List<WorkProgress> workProgressList = new ArrayList<>();
        if(StringUtils.isNotNull(list)){
            for (int i=0; i<list.size(); i++) {
                CommonUserVO userVO = list.get(i);
                WorkProgress workProgress = new WorkProgress();
                workProgress.setArrangeId(workArrange.getArrangeId());
                workProgress.setArrangeTitle(workArrange.getArrangeTitle());
                workProgress.setReceiveUserId(userVO.getUserId());
                workProgress.setReceiveDeptId(userVO.getDeptId());
                workProgress.setReceiveUser(userVO.getUserName());
                workProgress.setReceiveDept(userVO.getDeptName());
                workProgress.setEndDate(workArrange.getEndDate());
                workProgress.setStatus(CommonConstants.TO_BE_RECEIVED);
                workProgress.setCreateBy(ShiroUtils.getLoginName());
                workProgress.setCreateTime(DateUtils.getNowDate());
                workProgress.setUpdateBy(ShiroUtils.getLoginName());
                workProgress.setUpdateTime(DateUtils.getNowDate());
                if(StringUtils.equals(CommonConstants.ONGOING,workArrange.getStatus())){
                    workProgress.setReleaseStatus(CommonConstants.PUBLISHED);
                }else{
                    workProgress.setReleaseStatus(CommonConstants.UNPUBLISHED);
                }
                workProgressList.add(workProgress);
                //每50条进行新增插入
                if(workProgressList.size() % 50==0 || i==list.size()-1){
                    workArrangeMapper.batchWorkProgress(workProgressList);
                    workProgressList.clear();
                }
            }
            
            if(StringUtils.equals(CommonConstants.ONGOING,workArrange.getStatus())){
                //短信提示
                if(StringUtils.equals(CommonConstants.TIPS, workArrange.getSmsTips())){
                    AsyncManager.me().execute(createSmsTips(workArrange.getArrangeTitle(),list));
                }
                //平台提示
                if(StringUtils.equals(CommonConstants.TIPS, workArrange.getWebsiteTips())){
                    AsyncManager.me().execute(createWebsiteTips(list, 1));
                }
            }
        }
    }

    private TimerTask createSmsTips(String arrangeTitle, List<CommonUserVO> list) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    String message = commonUserVO.getUserName()+"，您好！在线监督平台提示: 您有一项工作任务(" + arrangeTitle + ")待上报";
                    String mobileNo = commonUserVO.getPhonenumber();
                    if(StringUtils.isNotEmpty(mobileNo)){
                        SmsUtil.sendMessage(message, mobileNo);
                    }
                }
            }
        };
    }

    private TimerTask createWebsiteTips(List<CommonUserVO> list, int num) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                for (CommonUserVO commonUserVO : list) {
                    WorkHandle  workHandle = new WorkHandle();
                    workHandle.setUserId(commonUserVO.getUserId());
                    workHandle.setType(CommonConstants.DEMEANOR);
                    workHandleService.insertOrUpdateWorkHandle(workHandle, num); //工作项+1
                }
            }
        };
    }

    /**
     * 通过工作安排ID修改工作安排状态
     * 
     * @param arrangeId 工作安排ID
     * @param status    工作状态（1草稿 2进行中 3已完成）
     * @return
     */
    @Override
    public int updateStatusByArrangeId(Long arrangeId, String status){
        String releaseStatus = CommonConstants.DRAFT.equals(status) ? CommonConstants.UNPUBLISHED:CommonConstants.PUBLISHED;
        workArrangeMapper.updateReleaseStatusByArrangeId(arrangeId, releaseStatus);
        int total = workArrangeMapper.updateStatusByArrangeId(arrangeId, status);
        String[] userIds = workArrangeMapper.selectReceiveUserByArrangeId(arrangeId);
        List<CommonUserVO> list = commonMapper.listActiveUserByIds(userIds);
        if(StringUtils.isNotNull(list)){
            if(CommonConstants.ONGOING.equals(status)){
                AsyncManager.me().execute(createWebsiteTips(list, 1));
            }else{
                AsyncManager.me().execute(createWebsiteTips(list, -1));
            }
        }
        return total;
    }

    /**
     * 获取工作安排汇总值
     * @param arrangeId
     * @return
     */
    @Override
	public String getWorkArrangeGatherById(Long arrangeId){
        String gatherData = "";
        WorkArrange workArrange = workArrangeMapper.selectWorkArrangeById(arrangeId);
        WorkTemplate workTemplate = workTemplateService.selectWorkTemplateById(workArrange.getTemplateId());
        String templateContent = workTemplate.getTemplateContent();
        JSONArray templateContentJsonArray = JSON.parseArray(templateContent);
        for (int i = 0; i < templateContentJsonArray.size(); i++) {
            templateContentJsonArray.getJSONObject(i).put("data", new JSONArray());
            templateContentJsonArray.getJSONObject(i).put("celldata", new JSONArray());
        }
        gatherData = templateContentJsonArray.toJSONString();
        return gatherData;
    }

}
